﻿package org.dm.res 
{
	import flash.events.EventDispatcher;
	import flash.utils.Dictionary;
	import flash.events.Event;
	import org.dm.general.ClassGather;
	import org.dm.net.DLoader;
	import org.dm.events.NetEvent;
	import org.dm.events.ResEvent;
	import org.dm.events.ApplicationEvent;
	import org.dm.utils.Map;
	
	/**
	 * ...
	 * @author Scott
	 */
	public class ResMgr extends EventDispatcher
	{
		private var _resList:Object;
		private var _resURLs:Array;
		private var _loader:DLoader;
		
		private var _curElement:int;
		private static var _instance:ResMgr;
		private static var _map:Map;
		
		public static function get instance():ResMgr
		{ 
			if(_instance==null)
			{
				var name:String = "org.dm.res.ResMgr";
				_instance = org.dm.general.ClassGather.getClass(name) as org.dm.res.ResMgr;
				if(_instance==null)
				{
					_instance = new org.dm.res.ResMgr();
					ClassGather.reg(name,_instance);
				}
			}
			return _instance;
		}
		
		public function ResMgr() 
		{
			_resList = new Object();
			_resURLs = new Array();
			_loader = new DLoader();
		}
		
		public function addRes(urls:Array=null):void
		{
			if (urls) _resURLs = urls;
		}
		
		public function start():void 
		{
			var num:int = _resURLs.length;
			if (num < 1) return;
			for each (var url:String in _resURLs)
			{
				var rr:DLoader = new DLoader();
				rr.request(url);
				rr.addEventListener(NetEvent.LOAD_COMPLETE, onComplete);				
			}
		}
		
		public function onComplete(e:NetEvent):void 
		{
			_curElement = 0;
			e.data.sharedEvents.addEventListener(ApplicationEvent.DOMAIN_DEFINE,getDomain); 
		}
		
		private function getDomain(event:Event):void
		{
			if (Object(event).defineClass == null)
			{
				this.dispatchEvent(new ResEvent(ResEvent.COMPLETE));
				return;
			}
			var cc:Array = Object(event).defineClass;
			var cname:String = Object(event).defineName;
			var cnamer:String;
			for each(var cla:* in cc)
			{
				cnamer = cla.toString().split(" ")[1];
				ClassGather.reg(cname + "." + cnamer.slice(0, cnamer.length - 1), cla);
				//trace(cname + "." + cnamer.slice(0, cnamer.length - 1) + "---------" + cla);
			}
		}
		
		public function get resList():Object
		{
			return this._resList; 
		}
		
		public function remove():void 
		{
			
		}
	}

}